package com.yangrd.airship.generator.support.utils;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;

/**
 * @author yangrd
 * @date 2021/11/9
 */
public class FileScanUtils {

    /**
     * scanForEach
     *
     * @param f
     * @param filenameFilter
     * @param fileConsumer
     */
    public static void scanForEach(File f, FilenameFilter filenameFilter, Consumer<File> fileConsumer) {
        if (Objects.nonNull(f)) {
            if (f.isDirectory()) {
                File[] fileArray = f.listFiles(filenameFilter);
                if (Objects.nonNull(fileArray)) {
                    for (File file : fileArray) {
                        scanForEach(file, filenameFilter, fileConsumer);
                    }
                }
            } else {
                fileConsumer.accept(f);
            }
        }
    }

    /**
     * scanListFile
     *
     * @param f
     * @param filenameFilter
     * @return
     */
    public static List<File> scanListFile(File f, FilenameFilter filenameFilter) {
        List<File> files = new ArrayList<>();
        scanForEach(f, filenameFilter, files::add);
        return files;
    }
}
